package server

import (
	"emailServer/service"
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
)

func StartEmailConsumer(conn *amqp.Connection) {
	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open channel: %v", err)
	}

	q, err := ch.QueueDeclare(
		"email",
		true, false, false, false, nil,
	)
	if err != nil {
		log.Fatalf("Failed to declare queue: %v", err)
	}

	msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil)
	if err != nil {
		log.Fatalf("Failed to register consumer: %v", err)
	}

	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
			log.Println(d)
			service.HandleEmailMessage(d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages.")
	select {} // block forever
}
